require 'digest'

class User
  include MongoMapper::Document

  #TODO: Necessary?
  timestamps!

  # username
  key :un, String, required: true, unique: true
  # real name
  key :rn, String, required: true
  # password
  key :pw, String, required: true, length: 64 # sha256 sum
  # (full) school name
  key :sc, String
  # logged in?
  #TODO: Should this be included?
  key :li, Boolean, default: false
  # e-mail
  key :em, String, required: true
  # languages
  many :user_lang
  # points
  key :pt, Integer
  # teacher or student
  key :t, Boolean, required: true, default: false

  # seed
  key :s, String
  # remember password, format {ip => seed, ...}
  key :rp, Hash, default: {}

  validates_uniqueness_of :em, allow_nil: true, allow_blank: true
  validates_format_of :em, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, allow_nil: true, allow_blank: true

  # Password related stuff
  #attr_accessible :password, :password_confirmation
  #validates :password, presence: true, confirmation: true, length: {within: 6..50}
  #before_save :encrypt_password

  def to_s
    <<-END
Username:  #{self.un}
Real Name: #{self.rn}
School:    #{self.sc}
Email:     #{self.em}
Languages:
#{
str = ""
self.user_lang.each do |ul|
  str += "- #{ul.la}\n  #{ul.cl}"
end
}
Teacher:   #{self.t ? "yes" : "no" }
#{self.to_str}
    END
  end

  private
  
  def encrypt_password
    self.pw = Digest::SHA2.hexdigest self.pw
  end

end

class UserLang
  include MongoMapper::EmbeddedDocument

  # language
  key :la, String, required: true
  # class
  key :cl, String, required: true
  # progress
  key :pr, Hash

  # user-defined vocab
  key :v, Hash, default: {}
  # user-defined grammar examples
  key :g, Hash, default: {}
  # user-defined activities
  key :a, Hash, default: {}
end
